package com.kuiandjie.web;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.Goal;
import com.kuiandjie.entity.Log;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.EmployeeService;
import com.kuiandjie.service.LogService;
import com.kuiandjie.service.TaskService;
import com.kuiandjie.util.DateUtil;

public class AddTaskServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String role = (String) session.getAttribute("role");
		Project curp = (Project) session.getAttribute("curp");
		
		if("leader".equals(role)) {
			String type = request.getMethod();
			Goal goal = (Goal) session.getAttribute("curgoal");
			if("POST".equals(type)) {
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				
				String taskName = request.getParameter("taskName");
				int empId = Integer.parseInt(request.getParameter("empId"));
				String beginTime = request.getParameter("beginTime");
				String endTime = request.getParameter("endTime");
				String state = request.getParameter("state");
				String level = request.getParameter("level");
				String desc = request.getParameter("desc");
				
				TaskService ts = new TaskService();
				ts.addTask(taskName, state, level, beginTime, endTime, desc, empId, goal.getId(), DateUtil.getNow());
				
				Employee e = (Employee) session.getAttribute("employee");
				Log log = new Log();
				log.setDesc("添加了任务<a href='task.jspx?gid=" + goal.getId() + "'>" + taskName + "</a>");
				log.setEmployeeId(e.getId());
				log.setProjectId(curp.getId());
				log.setTime(DateUtil.getNow());
				log.setName(e.getName());
				log.setPic(e.getPic());
				
				LogService ls = new LogService();
				ls.inserLog(log);
				
				request.setAttribute("msg", new Gson().toJson(log));
				request.getRequestDispatcher("msgflow.jspx").include(request, response);
				
				out.print("1");
				out.flush();
				out.close();
			} else {
				List<Employee> emList = getAllMember(curp.getId());
				request.setAttribute("emList", emList);
				request.getRequestDispatcher("WEB-INF/views/addtask.jsp").forward(request, response);
			}
		} else {
			response.sendRedirect("projectdetail.jspx");
		}
	}
	
	private List<Employee> getAllMember(int proId) {
		EmployeeService es = new EmployeeService();
		return es.findAllMember(proId);
	}
}
